package com.lmscn.lms.api.controller;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.lmscn.lms.api.model.*;
import com.lmscn.lms.api.util.BuildPaperUtil;
import com.lmscn.lms.api.util.CommonUtil;
import com.lmscn.lms.api.util.DesEncryptionUtil;
import com.lmscn.lms.api.util.JsonKit;
import com.lmscn.lms.commons.GlobalConst;

import java.text.DecimalFormat;
import java.util.*;

/**
 * Created by Czl on 2015/8/4.
 */
public class ClazzController extends Controller {

    /**
     * 我的班级
     */
    public void myClazz() {
        Long studentId = getParaToLong("studentId");
        List<Map<String, Object>> dataMapList = new ArrayList<Map<String, Object>>();
        List<ClazzStudent> clazzStudentList = ClazzStudent.dao.findByStudentId(studentId);
        Map<String, Object> dataMapNull = new HashMap<String, Object>();
        if (clazzStudentList != null && clazzStudentList.size() > 0) {
            for (ClazzStudent clazzStudent : clazzStudentList) {
                Map<String, Object> dataMap = new HashMap<String, Object>();
                Clazz clazz = Clazz.dao.findById(clazzStudent.getLong("class_id"));
                if(clazz != null) {
//                    clazz.set("img_path", CommonUtil.getClazzImgUrl(clazz));
                	clazz.set("img_path", GlobalConst.COURSE_IMG);
                    Long studentNum = ClazzStudent.dao.findStudentNum(clazzStudent.getLong("class_id"));
                    dataMap.put("clazz", clazz);
                    dataMap.put("studentNum", studentNum);
                    dataMap.put("error_code", 0);
                    dataMap.put("msg", "success");
                    Date endDate = clazz.getDate("end_time");
                    clazz.set("year", endDate.getTime());
                    dataMapList.add(dataMap);
                }
            }
        } else {
            dataMapNull.put("error_code", 1);
            dataMapNull.put("msg", "暂无加入任何班级");
            dataMapList.add(dataMapNull);
        }
        renderJson(JsonKit.listToJson(dataMapList, 39));
    }

    /**
     * 进入班级
     * 班级课程
     */
    public void myClazzCourse() {
        Long studentId = getParaToLong("studentId");  // 新加字段
        String studyGroup = getPara("studyGroup");    // 新加字段
        Long class_id = getParaToLong("classId");
        int pageNumber = getParaToInt("pageNumber");
        int pageSize = getParaToInt("pageSize");
        List<Map<String, Object>> dataMapList = new ArrayList<Map<String, Object>>();
        Map<String, Object> dataMapNull = new HashMap<String, Object>();
        Page<ClazzCourse> clazzCoursePage =
                ClazzCourse.dao.findClazzCoursePage(pageNumber, pageSize, class_id);
        List<ClazzCourse> clazzCourseList = clazzCoursePage.getList();
        if (clazzCourseList.size() > 0) {
            for (ClazzCourse clazzCourse : clazzCourseList) {
                Map<String, Object> dataMap = new HashMap<String, Object>();
                Long courseId = clazzCourse.getLong("course_id");
                CourseBase courseBase = CourseBase.dao.findById(courseId);
                
                CourseStudent courseStudent = CourseStudent.dao
                		.findByCourseIdAndStudentId(courseId, studentId);
                if (courseStudent==null) {
                	CourseStudent courseStu = getModel(CourseStudent.class);
                	String courseType = clazzCourse.getStr("course_type");
                	CourseStudent.dao.saveCourseStudent(courseStu, courseId,
                			studentId, class_id, "clazz", courseType, null, studyGroup);
                	dataMap.put("progress", 0);
                } else {
                	int minutes = courseBase.getInt("minutes");
                	long learnedHour = courseStudent.getLong("learned_hour");
                	DecimalFormat df=new DecimalFormat("0.0");  //设置保留位数
                	dataMap.put("progress", df.format( (float) learnedHour / minutes ));
                }
                
//              courseBase.set("url", CommonUtil.getMediaUrl(courseBase));
                courseBase.set("small_img", courseBase.getStr("small_img"));
                courseBase.set("large_img", courseBase.getStr("small_img"));
                dataMap.put("courseBase", courseBase);
                dataMap.put("courseLesson", courseBase.getCourseLesson());
                dataMap.put("courseLearningSetting", courseBase.getCourseLearningSetting());
                dataMapList.add(dataMap);
            }
        } else {
            dataMapNull.put("error_code", 1);
            dataMapNull.put("msg", "暂无课程");
            dataMapList.add(dataMapNull);
        }
        renderJson(JsonKit.listToJson(dataMapList, 39));
    }

    /**
     * 进入班级
     * 班级考试
     */
    public void myClazzExam() {
        Long studentId = getParaToLong("studentId");
        Long classId = getParaToLong("classId");
        Map<String, Object> dataMap = new HashMap<String, Object>();
        Clazz clazz = Clazz.dao.findById(classId);
        ClazzLearningSetting clazzLearningSetting=ClazzLearningSetting.dao.findByClazzId(classId);
        // 查询考试次数和最高分
        ClazzStudent clazzStudent = ClazzStudent.dao.findByClazzIdAndStuId(studentId, classId);
        int totalScore = clazzStudent.getInt("class_exam_score");
        Exam clazzExam = Exam.dao.getCourseExam(classId, "faceclazzexam");
        Long examedTimes = 0l;
        if(clazzExam != null) {
            // 已完成考试次数
            examedTimes = TestpaperResult.dao.getTestpaperCount(studentId, clazzExam.getLong("id"), "faceclazzexam", 1, -1);
        }
        if (clazz != null) {
            dataMap.put("clazz", clazz);
            dataMap.put("clazzLearningSetting",clazzLearningSetting);
            dataMap.put("totalScore", totalScore);
            dataMap.put("examedTimes", examedTimes);
            dataMap.put("times", clazzExam.getInt("times"));
            dataMap.put("error_code", 0);
            dataMap.put("msg", "success");
        } else {
            dataMap.put("error_code", 1);
            dataMap.put("msg", "无此班级");
        }
        renderJson(JsonKit.mapToJson(dataMap, 39));
    }

    /**
     * 进入班级
     * 班级通讯录
     */
    public void myClazzBook() {
        Long studentId = getParaToLong("studentId");
        Long classId = getParaToLong("classId");
        int pageNumber = getParaToInt("pageNumber");
        int pageSize = getParaToInt("pageSize");
        List<Map<String, Object>> dataMapList = new ArrayList<Map<String, Object>>();
        Page<ClazzStudent> clazzStudentPage = ClazzStudent.dao.findClazzStudentPage(pageNumber, pageSize, classId);
        List<ClazzStudent> clazzStudentList = clazzStudentPage.getList();
        if (clazzStudentList.size() > 0) {
            for (ClazzStudent clazzStudent : clazzStudentList) {
                Map<String, Object> dataMap = new HashMap<String, Object>();
                Student student = Student.dao.findById(clazzStudent.getLong("student_id"));
                student.set("post", DesEncryptionUtil.decryptStr(student.getStr("post")));
                student.set("email", DesEncryptionUtil.decryptStr(student.getStr("email")));
                student.set("mobile", DesEncryptionUtil.decryptStr(student.getStr("mobile")));
                student.set("little_img", CommonUtil.getHeadImgUrl(student));
                dataMap.put("student", student);
                dataMap.put("company", CommonUtil.getPhbPost(student));
                dataMapList.add(dataMap);
            }
        } else {
        }
        renderJson(JsonKit.listToJson(dataMapList, 39));
    }

    /**
     * 进入班级
     * 班级讨论
     */
    public void myClazzComment() {
        Long studentId = getParaToLong("studentId");
        Long classId = getParaToLong("classId");
        int pageNumber = getParaToInt("pageNumber");
        int pageSize = getParaToInt("pageSize");
        Map<String, Object> dataMap = new HashMap<String, Object>();
        List<Comment> commentList = Comment.dao.findPageByClassId(pageNumber, pageSize, classId).getList();
        Long totalNum = Comment.dao.getTotalComment("clazz",classId);
        if (commentList.size() > 0) {
            for(int i=0;i<commentList.size();i++) {
                Student student = Student.dao.findById(commentList.get(i).getLong("create_userid"));
                int num = (int) (Math.random() * 22) + 1;
                if (student.getStr("little_img") == null || "".equals(student.getStr("little_img"))) {
                    commentList.get(i).set("student_head_img", CommonUtil.getRandomHeadImgUrl(num));
                } else {
                    commentList.get(i).set("student_head_img", CommonUtil.getHeadImgUrl(student));
                }
            }
            dataMap.put("commentList", commentList);
            dataMap.put("commentNum", totalNum);
        }
        renderJson(JsonKit.mapToJson(dataMap, 39));
    }

    /**
     * 进入班级
     * 添加班级讨论
     */
    public void myClazzAddComment() {
        Long studentId = getParaToLong("studentId");
        Long classId = getParaToLong("classId");
        String content = getPara("content");
        Map<String, Object> dataMap = new HashMap<String, Object>();
        Comment comment = getModel(Comment.class);
        Student student = Student.dao.findById(studentId);
        Comment.dao.saveComment(comment, "clazz", classId, studentId, content,
                student.getStr("name"), DesEncryptionUtil.decryptStr(student.getStr("post")), student.getStr("little_img"));
        dataMap.put("error_code", 0);
        dataMap.put("msg", "success");
        renderJson(JsonKit.mapToJson(dataMap, 39));
    }

    /**
     * 进入班级考试
     */
    @Before(Tx.class)
    public void toClazzExam() {
        Long studentId = getParaToLong("studentId");
        Long classId = getParaToLong("classId");
        Map<String, Object> finalMap = new HashMap<String, Object>();//最终容器
        Map<String, Object> dataMapList = new HashMap<String, Object>();
        int answeredNum = 0;
        TestpaperResult testpaperResult = null;
        List<TestpaperResult> list = new ArrayList<TestpaperResult>();
        Map<String, Object> dataMap = new HashMap<String, Object>();
        //通过班级ID查看是否存在班级考试
        Exam exam = Exam.dao.getCourseExam(classId, "faceclazzexam");
        if (exam == null) {
            ClazzLearningSetting clazzLearningSetting = ClazzLearningSetting.dao.findByClazzId(classId);
            // 暂无考试 创建班级考试
            Exam clazz_exam = getModel(Exam.class);
            clazz_exam.saveClassExam(clazzLearningSetting, clazz_exam);
            dataMapList = BuildPaperUtil.BuildExamPaper(clazz_exam, studentId);
            list = TestpaperResult.dao.getTestpaperResult(studentId, clazz_exam.getLong("id"), "faceclazzexam", 0, -1, null);
            if (list.size() > 0) {
                testpaperResult = list.get(0);
            }
        } else {
            if (BuildPaperUtil.isTwiceExam(studentId, exam.getLong("id"), "faceclazzexam")) {// 判断考试几次
                //查看该学员是否存在未完成的试卷
                list = TestpaperResult.dao.getTestpaperResult(studentId, exam.getLong("id"), "faceclazzexam", 0, -1, null);
                if (list.size() > 0) {//如果大于0，说明存在未完成的答卷
                    testpaperResult = list.get(0);
                    //获取试卷都有哪些题目
                    List questionList = TestpaperItem.dao.getQuestionList(testpaperResult.getLong("testpaper_id"));
                    //获取学员已经答了哪些题。
                    List studentQuestionList = TestpaperItemResult.dao.getQuestionList(testpaperResult.getLong("testpaper_id"), studentId);
                    //把选项赋给题目
                    List questions = new ArrayList();
                    for (int i = 0; i < questionList.size(); i++) {
                        Question question = (Question) questionList.get(i);
                        List questionMetasList = QuestionMetas.dao.getQuestionMetas(Long.valueOf(question.getBigInteger("id").toString()));
                        for (int j = 0; j < questionMetasList.size(); j++) {
                            QuestionMetas questionMetas = (QuestionMetas) questionMetasList.get(j);
                            question.set("item" + (j + 1) + "_id", questionMetas.get("options"));
                        }
                        questions.add(question);
                    }
                    Map<String, Object> questionsMap = new HashMap<String, Object>();
                    questionsMap.put("question", questions);
                    questionsMap.put("answered", studentQuestionList);
                    dataMapList.put("questions", questionsMap);
                    dataMap.put("answeredNum", studentQuestionList.size());
                    answeredNum = studentQuestionList.size();
                } else {//学员不存在未完成的答卷，则直接生成试卷
                    dataMapList = BuildPaperUtil.BuildExamPaper(exam, studentId);
                    list = TestpaperResult.dao.getTestpaperResult(studentId, exam.getLong("id"), "faceclazzexam", 0, -1, null);
                    if (list.size() > 0) {
                        testpaperResult = list.get(0);
                    }
                }
                if (answeredNum == 0) {
                    dataMap.put("answeredNum", 0);
                }

            } else {
                dataMap.put("error_code", 1);
                dataMap.put("msg", "考试已超过限制次数");
                finalMap.put("testPaper", dataMap);
                renderJson(JsonKit.mapToJson(finalMap, 39));
            }
        }
        dataMap.put("limited_time", testpaperResult.getInt("limited_time"));
        dataMap.put("used_time", testpaperResult.getInt("used_time"));
        dataMap.put("testpaper_id", testpaperResult.getLong("testpaper_id"));
        dataMap.put("questionAbout", dataMapList);
        finalMap.put("testPaper", dataMap);
        renderJson(JsonKit.mapToJson(finalMap, 39));
    }

    /**
     * 进入班级练习
     */
    @Before(Tx.class)
    public void toClazzTest() {
        Long studentId = getParaToLong("studentId");
        Long classId = getParaToLong("classId");
        Map<String, Object> finalMap = new HashMap<String, Object>();//最终容器
        Map<String, Object> dataMapList = new HashMap<String, Object>();
        int answeredNum = 0;
        TestpaperResult testpaperResult = null;
        List<TestpaperResult> list = new ArrayList<TestpaperResult>();
        Map<String, Object> dataMap = new HashMap<String, Object>();
        //通过班级ID查看是否存在班级考试
        Test test = Test.dao.getTest(classId, "faceclazztest");
        if (test == null) {
            ClazzLearningSetting clazzLearningSetting = ClazzLearningSetting.dao.findByClazzId(classId);
            // 暂无考试 创建班级练习
            Test clazz_test = getModel(Test.class);
            clazz_test.saveClassTest(clazzLearningSetting, clazz_test);
            dataMapList = BuildPaperUtil.BuildTestPaper(clazz_test, studentId);
            list = TestpaperResult.dao.getTestpaperResult(studentId, clazz_test.getLong("id"), "faceclazztest", 0, -1, null);
            if (list.size() > 0) {
                testpaperResult = list.get(0);
            }
        } else {
            //查看该学员是否存在未完成的试卷
            list = TestpaperResult.dao.getTestpaperResult(studentId, test.getLong("id"), "faceclazztest", 0, -1, null);
            if (list.size() > 0) {//如果大于0，说明存在未完成的答卷
                testpaperResult = list.get(0);
                //获取试卷都有哪些题目
                List questionList = TestpaperItem.dao.getQuestionList(testpaperResult.getLong("testpaper_id"));
                //获取学员已经答了哪些题。
                List studentQuestionList = TestpaperItemResult.dao.getQuestionList(testpaperResult.getLong("testpaper_id"), studentId);
                //把选项赋给题目
                List questions = new ArrayList();
                for (int i = 0; i < questionList.size(); i++) {
                    Question question = (Question) questionList.get(i);
                    List questionMetasList = QuestionMetas.dao.getQuestionMetas(Long.valueOf(question.getBigInteger("id").toString()));
                    for (int j = 0; j < questionMetasList.size(); j++) {
                        QuestionMetas questionMetas = (QuestionMetas) questionMetasList.get(j);
                        question.set("item" + (j + 1) + "_id", questionMetas.get("options"));
                    }
                    questions.add(question);
                }
                Map<String, Object> questionsMap = new HashMap<String, Object>();
                questionsMap.put("question", questions);
                questionsMap.put("answered", studentQuestionList);
                dataMapList.put("questions", questionsMap);
                dataMap.put("answeredNum", studentQuestionList.size());
                answeredNum = studentQuestionList.size();
            } else {//学员不存在未完成的答卷，则直接生成试卷
                dataMapList = BuildPaperUtil.BuildTestPaper(test, studentId);
                list = TestpaperResult.dao.getTestpaperResult(studentId, test.getLong("id"), "faceclazztest", 0, -1, null);
                if (list.size() > 0) {
                    testpaperResult = list.get(0);
                }
            }
        }
        if (answeredNum == 0) {
            dataMap.put("answeredNum", 0);
        }
        dataMap.put("limited_time", testpaperResult.getInt("limited_time"));
        dataMap.put("testpaper_id", testpaperResult.getLong("testpaper_id"));
        dataMap.put("questionAbout", dataMapList);
        finalMap.put("testPaper", dataMap);
        renderJson(JsonKit.mapToJson(finalMap, 39));
    }

    /**
     * 查看班级考试成绩0930
     */
    public void clazzScore(){
        Long clazzId = getParaToLong("classId");
        Long studentId = getParaToLong("studentId");
        Exam clazzExam = Exam.dao.getCourseExam(clazzId, "faceclazzexam");
        TestpaperResult testpaperResult = TestpaperResult.dao.findMaxScore(studentId, clazzExam.getLong("id"), "faceclazzexam");
        Map<String,Object> dataMap = new HashMap<String,Object>();
        dataMap.put("score",testpaperResult.getInt("score"));
        dataMap.put("usedTime",testpaperResult.getInt("used_time"));
        dataMap.put("testpaperId",testpaperResult.getLong("testpaper_id"));
        renderJson(JsonKit.mapToJson(dataMap,39));
    }


}
